'use strict';

const Controller = require('egg').Controller;

// 定义创建接口的请求参数规则
const createRule = {
  categoryTag: 'string',
  categoryName: 'string',
};

class CategoryController extends Controller {
  async index() {
    const ctx = this.ctx;
    const { cms: { category } } = ctx.service;
    const data = await category.find(ctx.query);
    ctx.success({ ctx, data });
  }

  async show() {
    const ctx = this.ctx;
    const { cms: { category } } = ctx.service;
    const data = await category.findOne(ctx.params);
    ctx.success({ data });
  }

  async create() {
    const ctx = this.ctx;
    const { cms: { category } } = ctx.service;
    ctx.validate(createRule);
    try {
      const id = await category.create(ctx.request.body);
      const data = {
        id,
      };
      ctx.success({ data });
    } catch (error) {
      ctx.error({ detail: error });
    }
  }

  async update() {
    const ctx = this.ctx;
    const { cms: { category } } = ctx.service;
    const params = Object.assign({ id: ctx.params.id }, ctx.request.body);
    const data = await category.update(params);
    ctx.success({ ctx, data });
  }

  async destroy() {
    const ctx = this.ctx;
    const { cms: { category } } = ctx.service;
    const data = await category.destroy(ctx.params);
    ctx.success({ ctx, data });
  }
}

module.exports = CategoryController;
